package com.frxuexi.sign.view

import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.location.BDAbstractLocationListener
import com.baidu.location.BDLocation
import com.baidu.location.LocationClient
import com.baidu.location.LocationClientOption
import com.baidu.mapapi.map.BaiduMap
import com.baidu.mapapi.map.MapView
import com.baidu.mapapi.map.MyLocationData
import com.blankj.utilcode.util.SPUtils
import com.frxuexi.lib_base.mvi.BaseViewActivity
import com.frxuexi.sign.databinding.ActivityMapBinding


@Route(path = "/sign/MapActivity")
class MapActivity : BaseViewActivity<ActivityMapBinding>() {
    override val binding: ActivityMapBinding by lazy { ActivityMapBinding.inflate(layoutInflater) }

    var mapView: MapView? = null
    var mbaiduMap: BaiduMap? = null
    var mLocationClient: LocationClient? = null

    override fun initView() {
        SPUtils.getInstance().remove("loc")
        mapView = binding.map
        mbaiduMap = mapView?.map
        mbaiduMap?.isMyLocationEnabled = true

        LocationClient.setAgreePrivacy(true)
        //定位初始化
        mLocationClient = LocationClient(this)


//通过LocationClientOption设置LocationClient相关参数
        val option = LocationClientOption()
        option.isOpenGps = true // 打开gps

        option.setCoorType("bd09ll") // 设置坐标类型

        option.setScanSpan(1000)


//设置locationClientOption
        mLocationClient?.setLocOption(option)


//注册LocationListener监听器
        val myLocationListener = MyLocationListener()
        mLocationClient?.registerLocationListener(myLocationListener)
//开启地图定位图层
        mLocationClient?.start()


    }

    override fun onDestroy() {
        super.onDestroy()
        mLocationClient?.stop();
        mbaiduMap?.setMyLocationEnabled(false);
        mapView?.onDestroy();
        mapView = null;
    }


    inner class MyLocationListener : BDAbstractLocationListener() {
        override fun onReceiveLocation(location: BDLocation) {
            //mapView 销毁后不在处理新接收的位置
            if (location == null || mapView == null) {
                return
            }
            val locData = MyLocationData.Builder()
                .accuracy(location.radius) // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(location.direction).latitude(location.latitude)
                .longitude(location.longitude).build()
            mbaiduMap?.setMyLocationData(locData)
            Log.i("lr", "${location.latitude},${location.longitude}")
            

            if (SPUtils.getInstance().getString("loc", "").isNullOrEmpty()) {
                SPUtils.getInstance().put("loc", "${location.latitude},${location.longitude}")
            } else {
                mLocationClient?.stop();
            }
        }
    }


}